//
//  WKWebViewController.m
//  WeKeTang
//
//  Created by ichina on 2017/9/12.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKWebViewController.h"
#import "MyJSObject.h"
#import "WKUniversal.h"
#import "WKNetworkTools.h"
#import "WKFMDBTools.h"
#import "WKLoginHandel.h"
#import "WKMemberController.h"
#import "WKDownLoadModel.h"
#import "WKPlayerViewController.h"
#import "WKDownLoadManger.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <TencentOpenAPI/sdkdef.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import "NSString+KZExtension.h"
#import "TencentClient.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

@interface WKWebViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) JSContext *context;

@property (nonatomic, strong) WKFMDBTools *dbManger;

@property (nonatomic, assign) BOOL isDownloading;

@property (nonatomic, assign) BOOL index;
@property (nonatomic, assign) NSInteger downLoadCount;
@property (nonatomic, copy) NSString *section_voiceid;
@property (nonatomic, copy) NSString *section_name;
@property (nonatomic, strong) NSBlockOperation *main0peration;
@property (nonatomic, strong) NSOperationQueue *mainQueue;

@property (nonatomic, strong) UIProgressView *progressView;//进度条

@end

@implementation WKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setupUI];
}
- (void)setupUI{
    self.dbManger = [WKFMDBTools defaultFMDBToos];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    [self setLeftButtonWithImage:@"icon_return_white" highlightedImage:@"icon_return_white" target:self action:@selector(backAction)];
    self.index = 0;
    if (_isCollection) {
        self.navgationBar.barTintColor = RGBColor(40, 188, 203);
        self.statusbar.backgroundColor = RGBColor(40, 188, 203);
        [self middleTitleColor:[UIColor whiteColor]];
        self.navItem.title = @"优惠券使用规则";
    }else if (_isShare){
        self.navgationBar.barTintColor = [UIColor whiteColor];
        self.statusbar.backgroundColor = [UIColor whiteColor];
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
        [self middleTitleColor:[UIColor blackColor]];
        self.navItem.title = @"邀请好友";
        
    }
   // self.navItem.title = @"优惠券使用规则";
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64.5, kDeviceScreenWidth, kDeviceScreenHeight-64)];
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 64, kDeviceScreenWidth, 1)];
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 0.6f);
    self.progressView.backgroundColor = RGBColor(84, 178, 240);
    self.progressView.progressTintColor = [UIColor yellowColor];
    self.progressView.trackTintColor = [UIColor whiteColor];
    [self.view addSubview:self.progressView];
    
    NSURL *url = [NSURL URLWithString:self.urlStr];
    NSLog(@"邀请好友：%@",self.urlStr);
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    
    [self.webView loadRequest:request];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didCreateJSContext:) name:@"DidCreateContextNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(inviteFriendAction:) name:@"invite" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(backJSAction:) name:@"backAction" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(openMemberAction:) name:@"openMember" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(collectionAction:) name:@"collectionControl" object:nil];

}
- (void)backAction{
    self.webView.scrollView.delegate = nil;
    self.webView.delegate = nil;
    __weak typeof(self) weakSelf = self;
    
    if ([NSThread isMainThread]) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
    }
   
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [[NSNotificationCenter defaultCenter]removeObserverBlocks];
}
- (void)didCreateJSContext:(NSNotification *)notification {
    
    NSString *indentifier = [NSString stringWithFormat:@"indentifier%lud", (unsigned long)self.webView.hash];
    NSString *indentifierJS = [NSString stringWithFormat:@"var %@ = '%@'", indentifier, indentifier];
    [self.webView stringByEvaluatingJavaScriptFromString:indentifierJS];
    
    JSContext *context = notification.object;
    
    if (![context[indentifier].toString isEqualToString:indentifier]) return;
    
    _context = context;
    MyJSObject *jsObject = [MyJSObject objectWithWebView:self.webView];
    _context[@"SendToJs"] = jsObject;
}
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSLog(@"---------------%@",request.URL);
    
    return YES;
}

-(void)webViewDidStartLoad:(UIWebView *)webView{
    
    [self.progressView setProgress:0.6 animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    [self.progressView setProgress:1 animated:YES];
    self.progressView.hidden = YES;
    //[self middleTitleColor:[UIColor blackColor]];
    
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"标题:%@",title);
    //self.navItem.title = title;
    if ([title isEqualToString:@"none"]) {
        //self.navgationBar.hidden = YES;
    }
   //self.statusbar.backgroundColor = RGBColor(40, 188, 203);
}
#pragma mark - webView回到主页
- (void)backJSAction:(NSNotification*)nofi{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = nofi.userInfo;
    NSLog(@"返回：%@",dict);
    NSString *status = dict[@"status1"];
    NSLog(@"返回：%@",status);
    
  
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([status isEqualToString:@"1"]) {
            weakSelf.webView.scrollView.delegate = nil;
            if (weakSelf.collectionBlock) {
                weakSelf.collectionBlock();
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    });
    
}
#pragma mark - 收藏
- (void)collectionAction:(NSNotification*)nofi{
    NSDictionary *dict = nofi.userInfo;
    NSString *status = dict[@"str"];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showCustomAlertMessage:status];
    });
}
#pragma mark - 开通会员
- (void)openMemberAction:(NSNotification*)nofi{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = nofi.userInfo;
    NSString *status = [NSString stringWithFormat:@"%@",dict[@"str"]];
    dispatch_async(dispatch_get_main_queue(), ^{
        WKMemberController *memberVC = [[WKMemberController alloc]init];
        memberVC.isOpen = YES;
        memberVC.status = status;
        [weakSelf.navigationController pushViewController:memberVC animated:YES];
    });
    
    
}
#pragma mark - 邀请
- (void)inviteFriendAction:(NSNotification*)nofi{
    
    NSLog(@"邀请好友%@",nofi.userInfo);
    NSDictionary *dict = nofi.userInfo;
    NSString *inviteid = dict[@"inviteid"];
    NSString *url = dict[@"url"];
    int index = [inviteid intValue];
    
    switch (index) {
        case 1:
            [self shareQQFriendsWithUrl:url];
            break;
        case 2:
            [self shareQQZoneWithUrl:url];
            break;
        case 3:
            [self shareWechatFriendsCircleWithUrl:url];
            break;
        case 4:
            [self shareWechatFriendsWithUrl:url];
            break;
            
        default:
            break;
    }
}
- (void)shareQQFriendsWithUrl:(NSString*)url{
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *QQFriendsUrl = [NSString stringWithFormat:@"%@/%@/%@",kTestMainUrl,url,userid];
    dispatch_async(dispatch_get_main_queue(), ^{
        
         [[TencentClient shareTencentClient] sendToQQ:QQFriendsUrl title:@"【德智微课堂】新用户下载即送88元大礼包" desctiption:@"我正在德智微课堂学习名师课程，领大礼包学8700个初高中必考知识点!" imageUrl:kLogoUrl];
    });
      
}
- (void)shareQQZoneWithUrl:(NSString*)url{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
        NSString *QQZoneUrl = [NSString stringWithFormat:@"%@/%@/%@",kTestMainUrl,url,userid];
        
        [[TencentClient shareTencentClient] sendToQZone:QQZoneUrl title:@"【德智微课堂】新用户下载即送88元大礼包" desctiption:@"我正在德智微课堂学习名师课程，领大礼包学8700个初高中必考知识点!" imageUrl:kLogoUrl];

    });
   
}
- (void)shareWechatFriendsCircleWithUrl:(NSString*)url{
    __weak typeof(self) weakSelf = self;
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *WechatFriendsCircleUrl = [NSString stringWithFormat:@"%@/%@/%@",kTestMainUrl,url,userid];
    
    NSURL *imgUrl = [NSURL URLWithString:kLogoUrl];
    NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
    UIImage *image = [UIImage imageWithData:imgData];
    NSArray* imageArray = @[image];
    
    if (imageArray) {
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"我正在德智微课堂学习名师课程，领大礼包学8700个初高中必考知识点!" images:imageArray url:[NSURL URLWithString:WechatFriendsCircleUrl] title:@"【德智微课堂】新用户下载即送88元大礼包" type:SSDKContentTypeAuto];
        [ShareSDK share:SSDKPlatformSubTypeWechatTimeline parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
            
            [weakSelf dealShreResuleWithState:state error:error];
        }];
    }

    
}
- (void)shareWechatFriendsWithUrl:(NSString*)url{
    __weak typeof(self) weakSelf = self;
    
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *WechatFriendsUrl = [NSString stringWithFormat:@"%@/%@/%@",kTestMainUrl,url,userid];
    
    NSURL *imgUrl = [NSURL URLWithString:kLogoUrl];
    NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
    UIImage *image = [UIImage imageWithData:imgData];
    NSArray* imageArray = @[image];
    if (imageArray) {
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"我正在德智微课堂学习名师课程，领大礼包学8700个初高中必考知识点!" images:imageArray url:[NSURL URLWithString:WechatFriendsUrl] title:@"【德智微课堂】新用户下载即送88元大礼包" type:SSDKContentTypeAuto];
        [ShareSDK share:SSDKPlatformSubTypeWechatSession parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
            
            [weakSelf dealShreResuleWithState:state error:error];
        }];
    }

    
}
//处理分享结果
- (void)dealShreResuleWithState:(SSDKResponseState)state error:(NSError*)error{
    
    switch (state) {
        case SSDKResponseStateSuccess:{
            
            break;
        }
        case SSDKResponseStateFail:{
            [self showCustomAlertMessage:@"分享失败"];
            
            break;
        }
        case SSDKResponseStateCancel:{
            [self showCustomAlertMessage:@"分享取消"];
        }
        default:
            break;
    }
}
- (NSString*)changeCgrade:(NSString*)cgrade{
    
    NSString *typeid;
    if ([cgrade isEqualToString:@"1037"]||[cgrade isEqualToString:@"1038"]||[cgrade isEqualToString:@"1039"]) {
        
        typeid = @"1";
    }else if ([cgrade isEqualToString:@"1036"]){
        
        typeid = @"xiaoxue";
    }else if ([cgrade isEqualToString:@"1040"]||[cgrade isEqualToString:@"1041"]||[cgrade isEqualToString:@"1042"]){
        
        typeid = @"2";
    }
    return typeid;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
@implementation NSObject (JSTest)

- (void)webView:(id)unuse didCreateJavaScriptContext:(JSContext *)ctx forFrame:(id)frame {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DidCreateContextNotification" object:ctx];
}


@end
